<template>
  <div class="update-photo">
    <img :src="img" alt="损坏"  class="img" ref="img"/>
    <div class="toolbar">
        <span @click="$emit('cancel')">取消</span>
        <span @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  created () {},
  mounted () {
    // 要通过第三方插件操作dom所以在mounted来操作
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    onConfirm () {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true, // 静止背景点击
        duration: 0
      })
      // 基于服务端的裁剪使用getDate方法获取裁剪参数
      //   console.log(this.cropper.getData())
      // 纯客户端裁剪使用getCroppedCanvas方法获取裁剪文件的对象
      //   console.log(this.cropper.getCroppedCanvas())
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        try {
          // Content-Type multipart/form-data 一般照片文件是这种格式
          var formData = new FormData()
          // Pass the image file name as the third parameter if necessary.
          formData.append('photo', blob)// photo相当于建
          const res = await updateUserPhoto(formData)
          console.log(res)
          this.$emit('cancel')
          this.$emit('update-photo', res.data.data.photo)
          this.$toast.success('修改图片头像成功')
        } catch (err) {
          this.$toast.fail('修改图片头像失败')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
    .update-photo{
        background-color: #000;
        height: 100%;
        .img{
            display: block;
            /* This rule is very important, please don't ignore this */
            max-width: 100%;
        }
        .toolbar{
            display: flex;
            justify-content: space-between;
            position: fixed;
            bottom: 0;
            height: 88px;
            width: 100%;
            box-sizing: border-box;
            padding: 0 10px;
            font-size: 30px;
            span{
                display: inline-block;
                width: 90px;
                height: 90px;
                line-height: 90px;
                text-align: center;
                color: #fff;
            }
        }
    }
</style>
